import { Component, OnInit } from '@angular/core'
import { JsonApiService } from 'app/core/api/json-api.service' //http请求配置引入
import { Router, ActivatedRoute } from '@angular/router' //路由引入
import { config } from '../../shared/smartadmin.config'

declare var $: any
@Component({
  selector: 'sa-weixin-wx-pay2',
  templateUrl: './wx-pay2.component.html'
})
export class WXPay2Component implements OnInit {
  tableData: any[] = [] //table数据
  totalCount: number = 0 //分页总条数
  curPage: number = 1 //分页当前页
  pageSize: number = 10 //内置的分页每页条数
  tableSearch: any = {
    searchKey: '',
    companyType: '0',
    dateType: '1',
    payStatus: '',
    isDrawback: ''
  }
  typeExpense: any = ''
  startTime: string = ''
  endTime: string = ''
  selectedCompanyId: string = ''
  selectedCompanyName: string = ''
  deviceId: string = ''
  carNumber: string = ''
  delLimit: boolean = false
  editLimit: boolean = false
  refundLimit: boolean = false
  cancelOrderFlag: boolean = false
  refundControlFrom: any = {
    id: '',
    isDrawback: '0'
  }

  constructor(private jsonApiService: JsonApiService, private router: Router, private activatedRoute: ActivatedRoute) {
    activatedRoute.queryParams.subscribe(queryParams => {
      this.curPage = queryParams.nowPage || 1
    })
  }
  //初始化权限按钮
  initBtn() {
    let param = JSON.parse(decodeURIComponent(localStorage.getItem('cargpsw_contract:wx:pay2')))
    if (param) {
      for (let item of param) {
        if (item.sourceKey === 'wx2:pay:del' && item.parentId) {
          this.delLimit = true
        }
        if (item.sourceKey === 'wx2:pay:edit' && item.parentId) {
          this.editLimit = true
        }
        if (item.sourceKey === 'wx2:pay:refund' && item.parentId) {
          this.refundLimit = true
        }
      }
    }
  }
  // 接收子组件传递过来的数据
  getSelectTableTime(time) {
    this.startTime = time.startTime
    this.endTime = time.endTime
  }
  ngOnInit() {
    this.initBtn()
    this.load()
  }
  //Tab 切换
  tabChange(type) {
    this.typeExpense = type
    this.curPage = 1
    this.pageSize = 10
    this.tableData = []
    this.tableSearch.searchKey = ''
    this.load()
  }
  //table刷新
  refresh() {
    this.load()
  }
  //表格搜索
  table_search() {
    this.curPage = 1
    this.load()
  }
  //初始化加载list数据
  load() {
    let that = this
    this.cancelOrderFlag = false
    let timeCheck = common.correctTimeParams(this.startTime, this.endTime, 0)
    if (!timeCheck.status) {
      this.jsonApiService.message(timeCheck.message)
      return
    }
    let data = {
      pageSize: this.pageSize,
      nowPage: this.curPage,
      parameters: {
        companyId: this.selectedCompanyId,
        deviceId: this.deviceId,
        startTime: this.startTime,
        endTime: this.endTime,
        companyType: this.tableSearch.companyType,
        dateType: this.tableSearch.dateType,
        searchKey: common.stringTrim(this.tableSearch.searchKey),
        typeExpense: this.typeExpense,
        payStatus: this.tableSearch.payStatus,
        isDrawback: this.tableSearch.isDrawback
      }
    }
    let reqdata = 'gridPager=' + JSON.stringify(data)
    this.jsonApiService.http('repairOrder/queryRepairOrder.html', reqdata).subscribe(data => {
      if (data.isSuccess) {
        this.tableData = data.exhibitDatas
        this.totalCount = data.recordCount
        for (let item of this.tableData) {
          if (item.payStatus == 1) {
            this.cancelOrderFlag = true
          }
        }
      } else {
        this.jsonApiService.message(data.message)
      }
    })

    System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
      System.import('assets/js/select2-zh-CN.js').then(() => {
        that.initCarSelect2()
      })
    })
  }
  //报表导出
  exportTable() {
    if (!this.startTime || !this.endTime) {
      this.jsonApiService.message('请先选择开始时间或结束时间')
      return
    }
    const param = {
      dateType: this.tableSearch.dateType,
      startTime: this.startTime,
      endTime: this.endTime,
      companyId: this.selectedCompanyId,
      deviceId: this.deviceId,
      searchKey: this.tableSearch.searchKey.trim(),
      typeExpense: this.typeExpense,
      companyType: this.tableSearch.companyType,
      payStatus: this.tableSearch.payStatus,
      isDrawback: this.tableSearch.isDrawback
    }
    let timeCheck = common.correctTime(param, ['dateType', 'typeExpense'])
    if (!timeCheck.status) {
      this.jsonApiService.message(timeCheck.message)
      return
    }
    common.exprotDataFile(param, 'param', config.BaseURL + 'repairOrder/exportRepairOrder.html')
  }
  //月收款明细导出
  exportMonthTable() {
    if (!this.startTime || !this.endTime) {
      this.jsonApiService.message('请先选择开始时间或结束时间')
      return
    }
    var date1 = Date.parse(this.startTime)
    var date2 = Date.parse(this.endTime)
    var dateSpan = date2 - date1
    dateSpan = Math.abs(dateSpan)
    var iDays = Math.floor(dateSpan / (24 * 3600 * 1000))
    console.log(iDays)
    if (iDays > 35 || iDays == 35) {
      this.jsonApiService.message('时间相隔不能大于35天')
      return
    }
    const url =
      config.BaseURL +
      'suiniyStatistics/statisticsAppletsPayExport.html?startTime=' +
      this.startTime +
      '&endTime=' +
      this.endTime
    window.location.href = url
  }
  //月收款明细导出V2
  exportMonthTableV2() {
    if (!this.startTime || !this.endTime) {
      this.jsonApiService.message('请先选择开始时间或结束时间')
      return
    }
    var date1 = Date.parse(this.startTime)
    var date2 = Date.parse(this.endTime)
    var dateSpan = date2 - date1
    dateSpan = Math.abs(dateSpan)
    var iDays = Math.floor(dateSpan / (24 * 3600 * 1000))
    console.log(iDays)
    if (iDays > 35 || iDays == 35) {
      this.jsonApiService.message('时间相隔不能大于35天')
      return
    }
    const url =
      config.BaseURL +
      'suiniyStatistics/statisticsAppletsPayExportV2.html?startTime=' +
      this.startTime +
      '&endTime=' +
      this.endTime
    window.location.href = url
  }
  // 取消订单
  cancelRow(row) {
    //type 1:取消订单 2:撤销审核
    this.jsonApiService.confirm_message('确认取消订单?').then(() => {
      this.jsonApiService.http('repairOrder/cancelOrder.html', 'id=' + row.id + '&type=1').subscribe(data => {
        this.jsonApiService.message(data.message)
        if (data.success) {
          this.load()
        }
      })
    })
  }
  //	//删除
  delRow(row) {
    this.jsonApiService.confirm_message('此操作将永久删除数据,确认要删除?').then(() => {
      this.jsonApiService.http('repairOrder/deletedById.html', 'id=' + row.id).subscribe(data => {
        this.jsonApiService.message(data.message)
        if (data.success) {
          this.load()
        }
      })
    })
  }
  //分页回调
  paginate(e) {
    this.curPage = e.page + 1
    this.pageSize = e.rows
    this.load()
  }
  //公司选中回调
  companySelected(data) {
    this.selectedCompanyId = data.companyId
    this.selectedCompanyName = data.companyName
    this.deviceId = data.deviceId
    this.carNumber = data.carNumber
  }
  //初始化车辆
  // initCarNumbel() {
  // 	var that = this;
  // 	$("#carNumberSelect").select2({
  //         language : "zh-CN",
  //         minimumInputLength: 2,
  // 		allowClear: true,
  // 		placeholder:"请选择",
  // 		ajax: {
  //     		url: config.BaseURL+"stats/carListByCarNumber.html",
  //     		dataType: 'json',
  //     		delay: 50,
  //     		method: "POST",
  //     		xhrFields: {withCredentials: true},
  //     		data: function (params){return {"carNumber" :  params.term};},
  //     		processResults: function (data, params){
  //             	var options = new Array();
  //     		    $(data.data).each(function(index, car){
  // 	    		   	options.push({id : car.deviceId,text : car.carNumber})
  //     		    });
  //     		    return {results : options};
  //     		},
  //     		cache: true
  //         },
  //         templateResult : function (state){
  //         	if (!state.id) {return state.text;}
  //             var $state = $('<span><i class="fa fa-car green"></i>&nbsp;&nbsp;' + state.text + '</span>');
  //             return $state;
  //         },
  //    }).on("select2:select", function (e){
  //     	var data = e.params.data;
  //     	that.deviceId = data.id;
  // 		that.carNumber = data.text;
  //     });

  // }
  // //清除车辆选中值
  // del_carNumber(){
  // 	this.deviceId = '';
  // 	this.carNumber = '';
  // 	var str=$("<span class='select2-selection__placeholder'>请选择</span>");
  // 	$('#carNumberSelect').val("");
  // 	$("#select2-carNumberSelect-container").empty();
  // 	$("#select2-carNumberSelect-container").attr("title","");
  // 	$("#select2-carNumberSelect-container").prepend(str);
  // }

  cancelCheck(row) {
    //type 1:取消订单 2:撤销审核
    this.jsonApiService.confirm_message('小程序内的“待付款”维修订单将同步撤销，确认要撤销审核？').then(() => {
      this.jsonApiService.http('repairOrder/cancelOrder.html', 'id=' + row.id + '&type=2').subscribe(data => {
        this.jsonApiService.message(data.message)
        if (data.success) {
          this.load()
        }
      })
    })
  }
  examineId: any = '' //订单ID
  examineList: any = [] // 详细数组
  TotalPrice: any = 0 //总价格
  //审核 显示弹窗
  examineRow(row, modal) {
    this.TotalPrice = row.price / 100
    this.examineId = row.id
    this.examineList = []
    this.jsonApiService.http('repairOrder/getRepairNameById.html', 'id=' + row.id).subscribe(data => {
      if (data.success) {
        for (var i = 0; i < data.data.length; i++) {
          data.data[i].price = data.data[i].price / 100
          data.data[i].discountPrice = data.data[i].discountPrice / 100
          if (data.data[i].priceType == 0) {
            data.data[i].totalPrice = 0
          } else if (data.data[i].priceType == 1) {
            data.data[i].totalPrice = data.data[i].price * data.data[i].count
          } else if (data.data[i].priceType == 2) {
            data.data[i].totalPrice = data.data[i].discountPrice * data.data[i].count
          }
        }

        this.examineList = data.data
        modal.show()
      } else {
        this.jsonApiService.message(data.message)
      }
    })
  }
  reduceNum(target, index) {
    //次数为0 或者不支持累加 不可以进行减操作
    if (this.examineList[index].count == 0 || this.examineList[index].restrict == 0) {
      return
    }
    let numVal
    let val = Number(target.parentNode.parentNode.children[1].value)
    if (val < 1 || !val) {
      numVal = 1
    } else {
      if (val - 1 == 0) {
        numVal = 1
      } else {
        numVal = val - 1
      }
    }

    this.examineList[index].count = numVal
    this.computingMethod(index)
  }
  addNum(target, index) {
    //次数为0并且没有选择 或者不支持累加 不可以进行加操作
    if (this.examineList[index].count == 0 && this.examineList[index].priceType == 0) {
      return
    }
    if (this.examineList[index].restrict == 0) {
      return
    }
    let numVal
    let val = Number(target.parentNode.parentNode.children[1].value)
    if (val < 1 || !val) {
      numVal = 1
    } else {
      numVal = val + 1
    }
    this.examineList[index].count = numVal
    this.computingMethod(index)
  }
  //输入次数
  numInput(value, index) {
    this.examineList[index].count = value
    if (parseFloat(value).toString() == 'NaN') {
      if (this.examineList[index].priceType == 0) {
        this.examineList[index].count = 0
        $('#count' + index).val(0)
      } else {
        this.examineList[index].count = 1
        $('#count' + index).val(1)
      }
      return
    }
    var txg = /^[0-9]*[1-9][0-9]*$/
    if (!txg.test(value)) {
      if (this.examineList[index].priceType == 0) {
        this.examineList[index].count = 0
        $('#count' + index).val(0)
      } else {
        this.examineList[index].count = 1
        $('#count' + index).val(1)
      }
      return
    }
  }
  numChange(value, index) {
    this.examineList[index].count = value
    if (parseFloat(value).toString() == 'NaN') {
      if (this.examineList[index].priceType == 0) {
        this.examineList[index].count = 0
        $('#count' + index).val(0)
      } else {
        this.examineList[index].count = 1
        $('#count' + index).val(1)
      }
      return
    }
    var txg = /^[0-9]*[1-9][0-9]*$/
    if (!txg.test(value)) {
      if (this.examineList[index].priceType == 0) {
        this.examineList[index].count = 0
        $('#count' + index).val(0)
      } else {
        this.examineList[index].count = 1
        $('#count' + index).val(1)
      }
      return
    }
    this.computingMethod(index)
  }
  keyPress(event) {
    var keyCode = event.keyCode
    if (keyCode >= 48 && keyCode <= 57) {
      event.returnValue = true
    } else {
      event.returnValue = false
    }
  }
  clickSalesTypes(value, index, check) {
    if (check == true) {
      this.riseEditRowList[index].priceType = value
      this.riseEditRowList[index].count = 1
    } else {
      this.riseEditRowList[index].priceType = 0
      this.riseEditRowList[index].count = 0
    }
    this.computingMethods(index)
  }
  //公用方法
  computingMethods(num) {
    if (this.riseEditRowList[num].priceType == 0) {
      this.riseEditRowList[num].totalPrice = 0
    } else if (this.riseEditRowList[num].priceType == 1) {
      this.riseEditRowList[num].totalPrice = this.riseEditRowList[num].price * this.riseEditRowList[num].count
    } else if (this.riseEditRowList[num].priceType == 2) {
      this.riseEditRowList[num].totalPrice = this.riseEditRowList[num].discountPrice * this.riseEditRowList[num].count
    }

    let sumprice = 0
    for (let index = 0; index < this.riseEditRowList.length; index++) {
      const element = this.riseEditRowList[index]
      sumprice = Number(this.accSub(element.totalPrice, sumprice))
    }
    this.TotalPrice = sumprice
  }

  reduceNums(target, index) {
    //次数为0 或者不支持累加 不可以进行减操作
    if (this.riseEditRowList[index].count == 0 || this.riseEditRowList[index].restrict == 0) {
      return
    }
    let numVal
    let val = Number(target.parentNode.parentNode.children[1].value)
    if (val < 1 || !val) {
      numVal = 1
    } else {
      if (val - 1 == 0) {
        numVal = 1
      } else {
        numVal = val - 1
      }
    }

    this.riseEditRowList[index].count = numVal
    this.computingMethods(index)
  }
  addNums(target, index) {
    //次数为0并且没有选择 或者不支持累加 不可以进行加操作
    if (this.riseEditRowList[index].count == 0 && this.riseEditRowList[index].priceType == 0) {
      return
    }
    if (this.riseEditRowList[index].restrict == 0) {
      return
    }
    let numVal
    let val = Number(target.parentNode.parentNode.children[1].value)
    if (val < 1 || !val) {
      numVal = 1
    } else {
      numVal = val + 1
    }
    this.riseEditRowList[index].count = numVal
    this.computingMethods(index)
  }
  //输入次数
  numInputs(value, index) {
    this.riseEditRowList[index].count = value
    if (parseFloat(value).toString() == 'NaN') {
      if (this.riseEditRowList[index].priceType == 0) {
        this.riseEditRowList[index].count = 0
        $('#count' + index).val(0)
      } else {
        this.riseEditRowList[index].count = 1
        $('#count' + index).val(1)
      }
      return
    }
    var txg = /^[0-9]*[1-9][0-9]*$/
    if (!txg.test(value)) {
      if (this.riseEditRowList[index].priceType == 0) {
        this.riseEditRowList[index].count = 0
        $('#count' + index).val(0)
      } else {
        this.riseEditRowList[index].count = 1
        $('#count' + index).val(1)
      }
      return
    }
  }
  numChanges(value, index) {
    this.riseEditRowList[index].count = value
    if (parseFloat(value).toString() == 'NaN') {
      if (this.riseEditRowList[index].priceType == 0) {
        this.riseEditRowList[index].count = 0
        $('#count' + index).val(0)
      } else {
        this.riseEditRowList[index].count = 1
        $('#count' + index).val(1)
      }
      return
    }
    var txg = /^[0-9]*[1-9][0-9]*$/
    if (!txg.test(value)) {
      if (this.riseEditRowList[index].priceType == 0) {
        this.riseEditRowList[index].count = 0
        $('#count' + index).val(0)
      } else {
        this.riseEditRowList[index].count = 1
        $('#count' + index).val(1)
      }
      return
    }
    this.computingMethods(index)
  }

  clickSalesType(value, index, check) {
    if (check == true) {
      this.examineList[index].priceType = value
      this.examineList[index].count = 1
    } else {
      this.examineList[index].priceType = 0
      this.examineList[index].count = 0
    }
    this.computingMethod(index)
  }
  //公用方法
  computingMethod(num) {
    if (this.examineList[num].priceType == 0) {
      this.examineList[num].totalPrice = 0
    } else if (this.examineList[num].priceType == 1) {
      this.examineList[num].totalPrice = this.examineList[num].price * this.examineList[num].count
    } else if (this.examineList[num].priceType == 2) {
      this.examineList[num].totalPrice = this.examineList[num].discountPrice * this.examineList[num].count
    }

    let sumprice = 0
    for (let index = 0; index < this.examineList.length; index++) {
      const element = this.examineList[index]
      sumprice = Number(this.accSub(element.totalPrice, sumprice))
    }
    this.TotalPrice = sumprice
  }
  //浮点类型相加
  accSub(arg1, arg2) {
    var r1, r2, m, n
    try {
      r1 = arg1.toString().split('.')[1].length
    } catch (e) {
      r1 = 0
    }
    try {
      r2 = arg2.toString().split('.')[1].length
    } catch (e) {
      r2 = 0
    }
    m = Math.pow(10, Math.max(r1, r2))
    //last modify by deeka
    //动态控制精度长度
    n = r1 >= r2 ? r1 : r2
    return ((arg1 * m + arg2 * m) / m).toFixed(n)
  }
  closeAddBomModal(modal) {
    this.TotalPrice = 0
    this.examineId = ''
    this.examineList = []

    modal.hide()
  }
  submitRiseModal(modal) {
    const obj = {
      id: this.riseEditRowForm.id,
      repairOrder: JSON.parse(JSON.stringify(this.riseEditRowList))
    }
    let isChoose = false
    let totalPrice = 0
    for (const item of obj.repairOrder) {
      delete item.discount
      delete item.enabled
      delete item.index
      delete item.restrict
      item.totalPrice = item.totalPrice * 100
      totalPrice += item.totalPrice
      item.price = item.price * 100
      item.discountPrice = item.discountPrice * 100
      if (item.priceType !== 0) {
        isChoose = true
      }
    }
    if (!isChoose) {
      this.jsonApiService.message('至少需要选择一项任何维修方案')
      return
    }
    if (totalPrice === 0) {
      this.jsonApiService.message('维修方案总价不能为0')
      return
    }
    this.jsonApiService
      .http('repairOrder/editRepairedOrder.html', 'id=' + obj.id + '&repairOrder=' + JSON.stringify(obj.repairOrder))
      .subscribe(data => {
        this.jsonApiService.message(data.message)
        if (data.success) {
          this.closeRiseModal(modal)
          this.load()
        }
      })
  }
  submitModal(modal) {
    var repairOrderList = JSON.parse(JSON.stringify(this.examineList))
    var total = this.TotalPrice * 100
    var id = this.examineId
    var repairOrder = []
    for (var i = 0; i < repairOrderList.length; i++) {
      repairOrderList[i].totalPrice = repairOrderList[i].totalPrice * 100
      repairOrderList[i].price = repairOrderList[i].price * 100
      repairOrderList[i].discountPrice = repairOrderList[i].discountPrice * 100
      if (repairOrderList[i].priceType != 0) {
        repairOrder.push(repairOrderList[i])
      }
    }

    if (repairOrder.length == 0) {
      this.jsonApiService.message('至少需要选择一项任何维修方案')
      return
    }
    this.jsonApiService
      .http(
        'repairOrder/updateOrderById.html',
        'id=' + id + '&total=' + total + '&repairOrder=' + JSON.stringify(repairOrder)
      )
      .subscribe(data => {
        this.jsonApiService.message(data.message)
        if (data.success) {
          modal.hide()
          this.load()
        }
      })
  }
  editOrder: any = {
    payType: 0,
    typeExpense: 1,
    carNumber: '',
    deviceId: '',
    companyId: '',
    companyName: '',
    remark: '',
    id: ''
  }
  isPayType: boolean = true
  isTypeExpense: number = 1
  typeExpenseBack: number = 1
  validatorOptions = {
    excluded: [':disabled'],
    feedbackIcons: {
      valid: 'glyphicon glyphicon-ok',
      invalid: 'glyphicon glyphicon-remove',
      validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
      payType: {
        trigger: 'change',
        validators: {
          notEmpty: {
            message: '请选择支付类型'
          }
        }
      },
      typeExpense: {
        trigger: 'change',
        validators: {
          notEmpty: {
            message: '请选择费用类型'
          }
        }
      },
      carNumber: {
        validators: {
          notEmpty: {
            message: '请输入车牌号码'
          }
        }
      },
      companyName: {
        validators: {
          notEmpty: {
            message: '请输入所属厂区'
          }
        }
      }
    }
  }

  riseEditRowForm: any = {}
  riseEditRowList: any = []
  riseEditRow(row, modal): void {
    const _row = JSON.parse(JSON.stringify(row))
    this.riseEditRowForm = _row
    for (const item of _row.repairPlans) {
      item.price = item.price / 100
      item.discountPrice = item.discountPrice / 100
      if (item.priceType == 0) {
        item.totalPrice = 0
      } else if (item.priceType == 1) {
        item.totalPrice = item.price * item.count
      } else if (item.priceType == 2) {
        item.totalPrice = item.discountPrice * item.count
      }
    }
    this.riseEditRowList = _row.repairPlans

    modal.show()
  }

  // 编辑订单
  editRow(row, modal) {
    console.log(row, 'row')
    $('#editOrderForm').data('bootstrapValidator').resetForm()
    if (!row.payType) {
      row.payType = 0
    }
    this.editOrder.payType = row.payType
    this.editOrder.typeExpense = row.typeExpense
    this.editOrder.carNumber = row.carNumber
    this.editOrder.deviceId = row.deviceId
    if (this.editOrder.typeExpense == '2') {
      this.editOrder.companyId = row.companyId
      this.editOrder.companyName = row.companyName
    } else {
      this.editOrder.companyId = row.dockingFactoryId
      this.editOrder.companyName = row.dockingFactoryName
    }
    console.log(this.editOrder.companyName)

    this.editOrder.remark = row.remark
    this.editOrder.id = row.id
    if (row.payType == 0) {
      this.isPayType = true
    } else if (row.payType == 1) {
      this.isPayType = false
    }

    this.isTypeExpense = Number(row.typeExpense)
    this.typeExpenseBack = Number(row.typeExpense)

    //采用简单粗暴的方法清除;官方推荐的方法失效
    console.log(row.carNumber)
    if (this.editOrder.payType != 1) {
      $('#select2-carNumberSelect-container').empty()
      var str = $("<span class='select2-selection__placeholder'>" + row.carNumber + '</span>')
      $('#carNumberSelect').val(row.carNumber)
      $('#select2-carNumberSelect-container').attr('title', row.carNumber)
      $('#select2-carNumberSelect-container').prepend(str)
    }

    modal.show()
  }
  closeEditModal(modal) {
    $('#editOrderForm').data('bootstrapValidator').resetForm()
    modal.hide()
  }

  closeRiseModal(modal) {
    this.riseEditRowList = []
    this.riseEditRowForm = {}
    modal.hide()
  }

  submitEditModal(modal) {
    $('#editOrderForm').bootstrapValidator('validate') //开启验证
    let isValid = $('#editOrderForm').data('bootstrapValidator').isValid() //验证是否通过
    if (isValid) {
      // JSON.stringify(this.editOrder)
      let params = `payType=${this.editOrder.payType}&typeExpense=${
        this.editOrder.typeExpense
      }&carNumber=${this.editOrder.carNumber.replace(/\s*/g, '')}&deviceId=${this.editOrder.deviceId}&companyId=${
        this.editOrder.companyId
      }&companyName=${this.editOrder.companyName}&remark=${this.editOrder.remark}&id=${this.editOrder.id}`
      this.jsonApiService.http('repairOrder/editPayOrderV2.html', params).subscribe(data => {
        this.jsonApiService.message(data.message)
        console.log(data)
        if (data.success) {
          modal.hide()
          this.load()
        }
      })
    }
  }
  payTypeChange(val) {
    this.editOrder.payType = val
    if (val == 0) {
      this.isPayType = true
      this.isTypeExpense = this.typeExpenseBack
    } else {
      this.isPayType = false
      this.isTypeExpense = 1
    }
    // this.clearSelected()
    this.editOrder.typeExpense = this.isTypeExpense
    if (this.editOrder.payType != 1) {
      $('#select2-carNumberSelect-container').empty()
      var str = $("<span class='select2-selection__placeholder'>" + this.editOrder.carNumber + '</span>')
      $('#carNumberSelect').val(this.editOrder.carNumber)
      $('#select2-carNumberSelect-container').attr('title', this.editOrder.carNumber)
      $('#select2-carNumberSelect-container').prepend(str)
    }
  }
  typeExpenseChange(val) {
    // this.editOrder.carNumber = ''
    // this.editOrder.deviceId = ''
    // this.editOrder.companyId = ''
    // this.editOrder.companyName = ''
    // this.editOrder.remark = ''
    // this.delCarNumberSelect()
    this.isTypeExpense = Number(val)
    if (this.editOrder.payType == 0) {
      this.typeExpenseBack = this.isTypeExpense
    }
    this.editOrder.typeExpense = this.isTypeExpense

    $('#editOrderForm').data('bootstrapValidator').resetForm()
  }
  //新增或者编辑公司选中回调
  editCompanySelected(data) {
    this.editOrder.companyId = data.companyId || ''
    this.editOrder.companyName = data.companyName
    $('#editOrderForm').data('bootstrapValidator').resetForm()
  }
  carNumberChangeForm() {
    $('#editOrderForm').data('bootstrapValidator').resetForm()
  }
  // 清空所选
  clearSelected() {
    this.editOrder.typeExpense = 1
    this.isTypeExpense = 1
    this.editOrder.carNumber = ''
    this.editOrder.deviceId = ''
    this.editOrder.companyId = ''
    this.editOrder.companyName = ''
    this.editOrder.remark = ''
    this.delCarNumberSelect()
    $('#editOrderForm').data('bootstrapValidator').resetForm()
  }
  clickCarNumberSelect() {
    if (this.editOrder.typeExpense == '') {
      this.jsonApiService.message('请选选择费用类型!')
    }
  }
  //初始化select2 选项
  initCarSelect2() {
    var that = this
    $('#carNumberSelect')
      .select2({
        language: 'zh-CN',
        minimumInputLength: 4,
        allowClear: true,
        placeholder: '请选择',
        ajax: {
          url: config.BaseURL + 'repairOrder/findCarInfoByCarNumber.html',
          dataType: 'json',
          delay: 50,
          method: 'POST',
          xhrFields: { withCredentials: true },
          data: function (params) {
            return {
              carNumber: params.term.replace(/\s*/g, ''),
              type: that.editOrder.typeExpense == 3 ? 2 : that.editOrder.typeExpense
            }
          },
          processResults: function (data, params) {
            var options = new Array()
            var resultCarNumber = data.data.dockingInfo || []
            // 小于10个数量才判断重复
            if (resultCarNumber.length <= 10) {
              let arr = []
              let sameCar = []
              // 判断相同的车牌号
              for (let index = 0; index < resultCarNumber.length; index++) {
                let car = resultCarNumber[index]
                if (arr.indexOf(car.carNumber) != -1) {
                  sameCar.push(car.carNumber)
                } else {
                  arr.push(car.carNumber)
                }
              }
              $(resultCarNumber).each(function (index, car) {
                if (sameCar.indexOf(car.carNumber) != -1) {
                  options.push({
                    id: car.deviceId,
                    text: car.carNumber + '[' + car.dockingFactoryName + ']' + '[' + car.deviceId + ']',
                    dockingFactoryName: car.dockingFactoryName,
                    dockingFactoryId: car.dockingFactoryId
                  })
                } else {
                  options.push({
                    id: car.deviceId,
                    text: car.carNumber,
                    dockingFactoryName: car.dockingFactoryName,
                    dockingFactoryId: car.dockingFactoryId
                  })
                }
              })
            } else {
              $(resultCarNumber).each(function (index, car) {
                options.push({
                  id: car.deviceId,
                  text: car.carNumber,
                  dockingFactoryName: car.dockingFactoryName,
                  dockingFactoryId: car.dockingFactoryId
                })
              })
            }
            return {
              results: options //获取查询后的结果
            }
          },
          cache: true
        },
        templateResult: function (state) {
          if (!state.id) {
            return state.text
          }
          var $state = $('<span><i class="fa fa-car green"></i>&nbsp;&nbsp;' + state.text + '</span>')
          return $state
        }
      })
      .on('select2:select', function (e) {
        var data = e.params.data
        that.editOrder.deviceId = data.id
        that.editOrder.companyName = data.dockingFactoryName
        that.editOrder.companyId = data.dockingFactoryId
        if (data.text.indexOf('[') > 0) {
          that.editOrder.carNumber = data.text.split('[')[0]
        } else {
          that.editOrder.carNumber = data.text
        }
        $('#editOrderForm').data('bootstrapValidator').resetForm()
        // that.editOrder.carNumber = data.text;
        // $("#carNumberSelect2").val(that.editOrder.deviceId).change();
      })
  }

  //擦除用户所选值
  delCarNumberSelect() {
    this.editOrder.deviceId = ''
    this.editOrder.carNumber = ''
    //采用简单粗暴的方法清除;官方推荐的方法失效
    var str = $("<span class='select2-selection__placeholder'>请选择</span>")
    $('#carNumberSelect').val('')
    $('#select2-carNumberSelect-container').empty()
    $('#select2-carNumberSelect-container').attr('title', '')
    $('#select2-carNumberSelect-container').prepend(str)
    this.load()
  }
  updateRecordList: any[] = []
  // 更新记录弹窗
  updateRecord(row, modal) {
    this.jsonApiService.http('repairOrder/getPayOrderEditLogList.html', 'id=' + row.id).subscribe(data => {
      console.log(data)
      modal.show()
      this.updateRecordList = data.data || []
    })
  }
  updateRecordClose(modal) {
    modal.hide()
  }

  /*
   * 退款
   */
  refundRow(row, modal) {
    modal.show()
    this.refundControlFrom.id = row.id
  }

  isDrawbackChange(val) {
    this.refundControlFrom.isDrawback = val
  }

  /*
   * 关闭弹窗
   */
  modalIsDrawbackClose(modal) {
    modal.hide()
    this.refundControlFrom.isDrawback = '0'
  }
  /*
   * form提交
   */
  deviceControlSubmit(modal) {
    let url = 'repairOrder/drawbackOrder.html'
    this.jsonApiService.http_obj(url, this.refundControlFrom).subscribe(data => {
      this.jsonApiService.message(data.message)
      if (data.success) {
        this.load()
        this.modalIsDrawbackClose(modal)
      }
    })
  }
}
